package controller;

import entity.RosterEntry;
import entity.Staff;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.RosterEntryFacade;
import session.StaffFacade;


/**
 *
 * @author Elise
 */
public class RosterServlet extends HttpServlet {

    @EJB
    private RosterEntryFacade rosterEntryFacade;
    @EJB
    private StaffFacade staffFacade;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Process request (Perform actions, set response attributes, set path for forward dispatch)
        String pathInfo = request.getPathInfo();
        pathInfo = (pathInfo == null) ? "" : pathInfo;
        String fdPath = null;
        Pattern p1 = Pattern.compile("/(\\d+)/(\\d+)"); // matches to /id/action
        Matcher m1 = p1.matcher(pathInfo);
        m1.find();
        Integer yearID;
        Integer weekID;
        try {
            yearID = Integer.parseInt(m1.group(1));
        } catch (Exception ex) {
            yearID = null;
        }
        try {
            weekID = Integer.parseInt(m1.group(2));
        } catch(IllegalStateException ex) {
            weekID = null;
        }

        Pattern p2 = Pattern.compile("/(\\d+)(/(\\w+))?"); // matches to /id/action
        Matcher m2 = p2.matcher(pathInfo);
        m2.find();
        Long rosterEntryId;
        String action;
        try {
            rosterEntryId = Long.parseLong(m2.group(1));
        } catch (Exception ex) {
            rosterEntryId = null;
        }
        try {
            action = m2.group(3);
        } catch(IllegalStateException ex) {
            action = null;
        }

        ////////////////////////////////////////////////////////////////////////
        //CREATE
        if(pathInfo.equals("/new")) {
            fdPath = "/WEB-INF/view/roster/newRosterEntry.jsp";
            request.setAttribute("staff", staffFacade.findAll());
        }
        ////////////////////////////////////////////////////////////////////////
        //READ
        else if (pathInfo.equals("")) {
            //Default view
            Calendar calNow = GregorianCalendar.getInstance();
            request.setAttribute("week", calNow.get(calNow.WEEK_OF_YEAR));
            request.setAttribute("year", calNow.get(calNow.YEAR));
            request.setAttribute("roster", rosterEntryFacade.queryFindAllForWeek(calNow.get(calNow.WEEK_OF_YEAR)));

            //Obtain next week/last week values.
            int lastWeek = calNow.get(calNow.WEEK_OF_YEAR) - 1;
            int nextWeek = calNow.get(calNow.WEEK_OF_YEAR) + 1;
            int lastYear = calNow.get(calNow.YEAR);
            int nextYear = calNow.get(calNow.YEAR);

            if(lastWeek <= 0){
                GregorianCalendar cal = new GregorianCalendar(lastYear-1, 11, 31);
                lastWeek = cal.get(cal.WEEK_OF_YEAR);
                lastYear = lastYear - 1;
            }
            if(nextWeek > 52){
                GregorianCalendar cal = new GregorianCalendar(lastYear, 11, 31);
                if(cal.get(cal.WEEK_OF_YEAR)!=53){
                    nextWeek = 1;
                    nextYear = nextYear + 1;
                }
            }
            request.setAttribute("nextWeek", nextWeek);
            request.setAttribute("lastWeek", lastWeek);
            fdPath = "/WEB-INF/view/roster/weekView.jsp";

            fdPath = "/WEB-INF/view/roster/default.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        else if (pathInfo.equals("/staffView")) {
            //TODO: Generate query for staff.
            request.setAttribute("roster", rosterEntryFacade.findAll());
            fdPath = "/WEB-INF/view/roster/staffView.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        else if(yearID !=null && weekID !=null){
            //Display relevant week roster.
            int lastWeek = weekID - 1;
            int nextWeek = weekID + 1;
            int lastYear = yearID;
            int nextYear = yearID;
            request.setAttribute("roster", rosterEntryFacade.queryFindAllForWeek(weekID));
            request.setAttribute("week", weekID);
            request.setAttribute("year", yearID);

            if(weekID < 1){
                lastYear = yearID - 1;
                GregorianCalendar cal = new GregorianCalendar(lastYear, 11, 31);
                lastWeek = cal.get(cal.WEEK_OF_YEAR);
            }
            if(weekID >= 53){
                GregorianCalendar cal = new GregorianCalendar(yearID, 11, 31);
                if(cal.get(cal.WEEK_OF_YEAR)<53){
                    nextWeek = 1;
                    nextYear = yearID + 1;
                }
            }
            request.setAttribute("nextWeek", nextWeek);
            request.setAttribute("lastWeek", lastWeek);
            request.setAttribute("nextYear", nextYear);
            request.setAttribute("lastYear", lastYear);
            fdPath = "/WEB-INF/view/roster/weekView.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        // UPDATE
        else if (rosterEntryId != null && action.equals("edit")) {

            //TODO: Finish edit
            RosterEntry rosterEntry = rosterEntryFacade.find(rosterEntryId);
                request.setAttribute("entry", rosterEntry);
                request.setAttribute("selShift", rosterEntry.getShift());
                request.setAttribute("selDay", rosterEntry.getDay());
                request.setAttribute("selMonth", rosterEntry.getMonth());
                request.setAttribute("selStartHrs", rosterEntry.getSHours());
                fdPath = "/WEB-INF/view/roster/editRosterEntry.jsp";
        }

        // Forward dispatch
        if(fdPath == null)
            fdPath = "/WEB-INF/jspf/error/404.jsp";

        request.getRequestDispatcher(fdPath).forward(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        pathInfo = (pathInfo == null) ? "" : pathInfo;
        String fdPath = null;
        Pattern p1 = Pattern.compile("/(\\d+)/(\\d+)"); // matches to /year/week
        Matcher m1 = p1.matcher(pathInfo);
        m1.find();
        Integer yearID;
        Integer weekID;
        try {
            yearID = Integer.parseInt(m1.group(1));
        } catch (Exception ex) {
            yearID = null;
        }
        try {
            weekID = Integer.parseInt(m1.group(2));
        } catch(IllegalStateException ex) {
            weekID = null;
        }

        Pattern p2 = Pattern.compile("/(\\d+)(/(\\w+))?"); // matches to /id/action
        Matcher m2 = p2.matcher(pathInfo);
        m2.find();
        Long rosterEntryId;
        String action;
        try {
            rosterEntryId = Long.parseLong(m2.group(1));
        } catch (Exception ex) {
            rosterEntryId = null;
        }
        try {
            action = m2.group(3);
        } catch(IllegalStateException ex) {
            action = null;
        }
        ////////////////////////////////////////////////////////////////////////
        //CREATE
        if(pathInfo.equals("/new")) {

            //Add roster entry to database.
            //Date objects
            int day = Integer.parseInt(request.getParameter("day"));
            int month = Integer.parseInt(request.getParameter("month"));
            int year = Integer.parseInt(request.getParameter("year"));
            int stHours = Integer.parseInt(request.getParameter("stHours"));
            int stMinutes = Integer.parseInt(request.getParameter("stMinutes"));
            int endHours = Integer.parseInt(request.getParameter("endHours"));
            int endMinutes = Integer.parseInt(request.getParameter("endMinutes"));

            GregorianCalendar start = new GregorianCalendar();
            start.set(year, month, day, stHours, stMinutes);

            GregorianCalendar end = new GregorianCalendar();
            end.set(year, month, day, endHours, endMinutes);

            String[] staff = request.getParameterValues("staffID");

            ArrayList<Staff> staffList = new ArrayList<Staff>();
            for(int i=0; i<staff.length; i++){
                staffList.add(staffFacade.find(Long.parseLong(staff[i])));
            }

            RosterEntry rosterEntry = new RosterEntry(
                                Integer.parseInt(request.getParameter("shift")),
                                start,
                                end,
                                staffList);
            try {
                rosterEntryFacade.create(rosterEntry);
                request.setAttribute("rosterEntryName", "Shift" + request.getParameter("shift"));
            } catch(Exception ex) {
                request.setAttribute("addRosterEntryFailureFlag", true);
            }
           
            request.setAttribute("staff", staffFacade.findAll());
            fdPath = "/WEB-INF/view/roster/newRosterEntry.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        //READ
        else if (pathInfo.equals("")) {
            //Default view - shows current week of roster entries.
            Calendar calNow = GregorianCalendar.getInstance();
            request.setAttribute("week", calNow.get(calNow.WEEK_OF_YEAR));
            request.setAttribute("year", calNow.get(calNow.YEAR));
            request.setAttribute("roster", rosterEntryFacade.queryFindAllForWeek(calNow.get(calNow.WEEK_OF_YEAR)));

            //Obtain next week/last week values.
            int lastWeek = calNow.get(calNow.WEEK_OF_YEAR) - 1;
            int nextWeek = calNow.get(calNow.WEEK_OF_YEAR) + 1;
            int lastYear = calNow.get(calNow.YEAR);
            int nextYear = calNow.get(calNow.YEAR);

            if(lastWeek <= 0){
                GregorianCalendar cal = new GregorianCalendar(lastYear-1, 11, 31);
                lastWeek = cal.get(cal.WEEK_OF_YEAR);
                lastYear = lastYear - 1;
            }
            if(nextWeek > 52){
                GregorianCalendar cal = new GregorianCalendar(lastYear, 11, 31);
                if(cal.get(cal.WEEK_OF_YEAR)!=53){
                    nextWeek = 1;
                    nextYear = nextYear + 1;
                }
            }
            request.setAttribute("nextWeek", nextWeek);
            request.setAttribute("lastWeek", lastWeek);
            request.setAttribute("nextYear", nextYear);
            request.setAttribute("lastYear", lastYear);
            fdPath = "/WEB-INF/view/roster/default.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        else if(yearID !=null && weekID !=null){
            int lastWeek = weekID - 1;
            int nextWeek = weekID + 1;
            int lastYear = yearID;
            int nextYear = yearID;
            request.setAttribute("roster", rosterEntryFacade.queryFindAllForWeek(weekID));
            request.setAttribute("week", weekID);
            request.setAttribute("year", yearID);

            if(weekID < 1){
                lastYear = yearID - 1;
                GregorianCalendar cal = new GregorianCalendar(lastYear, 11, 31);
                lastWeek = cal.get(cal.WEEK_OF_YEAR);
            }
            if(weekID >= 53){
                GregorianCalendar cal = new GregorianCalendar(yearID, 11, 31);
                if(cal.get(cal.WEEK_OF_YEAR)<53){
                    nextWeek = 1;
                    nextYear = yearID + 1;
                }
            }
            request.setAttribute("nextWeek", nextWeek);
            request.setAttribute("lastWeek", lastWeek);
            fdPath = "/WEB-INF/view/roster/weekView.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        else if (pathInfo.equals("/,,,,,,,,,,,,,,,,,,,,,,,,,,,,")) {

        }
        ////////////////////////////////////////////////////////////////////////
        //UPDATE
        else if (rosterEntryId != null && action.equals("edit")) {
            RosterEntry rosterEntry = rosterEntryFacade.find(rosterEntryId);
                try {
                    // Edit roster entry entity with updated data
                    rosterEntry.setShift(Integer.parseInt(request.getParameter("shift")));

                    int day = Integer.parseInt(request.getParameter("day"));
                    int month = Integer.parseInt(request.getParameter("month"));
                    int year = Integer.parseInt(request.getParameter("year"));
                    int stHours = Integer.parseInt(request.getParameter("stHours"));
                    int stMinutes = Integer.parseInt(request.getParameter("stMinutes"));
                    int endHours = Integer.parseInt(request.getParameter("endHours"));
                    int endMinutes = Integer.parseInt(request.getParameter("endMinutes"));

                    GregorianCalendar start = new GregorianCalendar();
                    start.set(year, month, day, stHours, stMinutes);
                    rosterEntry.setStartTime(start);

                    GregorianCalendar end = new GregorianCalendar();
                    end.set(year, month, day, endHours, endMinutes);
                    rosterEntry.setEndTime(end);

                    String[] staff = request.getParameterValues("staffID");

                    ArrayList<Staff> staffList = new ArrayList<Staff>();
                    for(int i=0; i<staff.length; i++){
                        staffList.add(staffFacade.find(Long.parseLong(staff[i])));
                    }
                    rosterEntry.setStaff(staffList);

                    // Merge new phone entity with existing record with productId
                    rosterEntryFacade.edit(rosterEntry);
                    request.setAttribute("entryName", "Shift"+rosterEntry.getShift());
                    request.setAttribute("entry", rosterEntry);
                } catch (Exception ex) {
                    request.setAttribute("updateRosterEntryFailureFlag", true);
                }
                fdPath = "/WEB-INF/view/roster/editRosterEntry.jsp";
        }
        // Forward dispatch
        if(fdPath == null)
            fdPath = "/WEB-INF/jspf/error/404.jsp";

        request.getRequestDispatcher(fdPath).forward(request, response);
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Servlet to handle all requests with URL /catalogue/*";
    }// </editor-fold>

}
